package com.lkd.shoppingcart.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.lkd.shoppingcart.entity.Cart;
import com.lkd.shoppingcart.entity.Product;
import com.lkd.shoppingcart.entity.User;
import com.lkd.shoppingcart.service.CartService;
import com.lkd.shoppingcart.service.ProductService;
import com.lkd.shoppingcart.service.impl.CartServiceImpl;
import com.lkd.shoppingcart.service.impl.ProductServiceImpl;
import com.lkd.shoppingcart.utils.WebUtils;

@WebServlet("/cartServlet")
public class CartServlet extends BaseServlet {

	private static final long serialVersionUID = 1L;
	private ProductService productService = new ProductServiceImpl();
	private CartService cartService = new CartServiceImpl();
	
	/**
	 * 向购物车添加项
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		User user = (User) req.getSession().getAttribute("user");
		int userId = user.getId();
        int productId = WebUtils.parseInt(req.getParameter("productId"), 0);        
        int quantity = WebUtils.parseInt(req.getParameter("quantity"), 1);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        if (cartService.cartExists(userId, productId)) {
        	resultMap.put("alreadyExists", true);
        } else {
            cartService.addToCart(userId, productId, quantity);
            
            Cart cart = cartService.queryByUserId(userId);
            req.getSession().setAttribute("cart", cart);

            // 返回购物车总的商品数量和最后一个添加的商品名称
            Product product = productService.queryProductById(productId);
            resultMap.put("productsCount", cartService.queryForCount(userId));
            resultMap.put("lastName", product.getName());
        }
        Gson gson = new Gson();
        String resultMapJsonString = gson.toJson(resultMap);

        resp.getWriter().write(resultMapJsonString);
	}
	
	/**
	 * 从购物车中移除项
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	protected void removeItem(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		User user = (User) req.getSession().getAttribute("user");
		int userId = user.getId();
        int productId = WebUtils.parseInt(req.getParameter("productId"), 1);
        cartService.removeById(userId, productId);
        Cart cart = cartService.queryByUserId(userId);
        req.getSession().setAttribute("cart", cart);
        resp.sendRedirect(req.getHeader("Referer"));
	}
	
	/**
	 * 清空购物车
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	protected void removeAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		User user = (User) req.getSession().getAttribute("user");
		int userId = user.getId();
		cartService.removeByUserId(userId);
		Cart cart = cartService.queryByUserId(userId);
        req.getSession().setAttribute("cart", cart);
		resp.sendRedirect(req.getHeader("Referer"));
	}
	
	/**
	 * 修改商品购买数量
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	protected void changeQuantity(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		User user = (User) req.getSession().getAttribute("user");
		int userId = user.getId();
        int productId = WebUtils.parseInt(req.getParameter("productId"), 1);
        int quantity = WebUtils.parseInt(req.getParameter("quantity"), 1);
        cartService.updateQuantityById(userId, productId, quantity);
        Cart cart = cartService.queryByUserId(userId);
        req.getSession().setAttribute("cart", cart);
        resp.sendRedirect(req.getHeader("Referer"));
	}
	
	/**
	 * 获取用户购物车信息
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void showCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		HttpSession session = req.getSession();
		User user = (User) session.getAttribute("user");
		Cart cart = cartService.queryByUserId(user.getId());
		session.setAttribute("cart", cart);
		req.getRequestDispatcher("/pages/cart/cart.jsp").forward(req, resp);
	}

}
